using AutoMapper;
using B.S.BaseData.Api.Write.Application.Command.Deaths;
using B.S.BaseData.Domain;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;
using MediatR;
using SmartTracking.Domain.ZXL;

namespace B.S.BaseData.Api.Write.Application.CommandHandler.Deaths
{
    public class CreateDeathCommandHandler : IRequestHandler<CreateDeathCommand, ApiResult<int>>
    {


        private readonly IBaseRepository<Death> death;
        private readonly IBaseRepository<Deathhead> deathheads;
        private readonly IMapper map;

        public CreateDeathCommandHandler(IBaseRepository<Death> death, IMapper map, IBaseRepository<Deathhead> deathheads)
        {
            this.death = death;
            this.map = map;
            this.deathheads = deathheads;
        }

        public async Task<ApiResult<int>> Handle(CreateDeathCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            

            try
            {

                

                if (request.DeathsList != null && request.DeathsList.Count > 0)
                {
                    Deathhead deathhead = new Deathhead();

                    deathhead.Deathdate = request.Deathdate;
                    deathhead.SheepType = request.SheepType;
                    deathhead.Documentnumber = request.Documentnumber;
                    

                    await deathheads.AddAsync(deathhead);

                    

                    int r = await death.AddRangeAsync(request.DeathsList);

                    if (r == 0)
                    {
                        res.Message = "创建死亡失败";
                        res.Code = ApiEnum.新增失败;
                    }
                    else
                    {
                        res.Message = "创建死亡成功";
                        res.Code = ApiEnum.新增成功;
                    }
                }
                else
                {
                    res.Message = "死亡列表不能为空";
                    res.Code = ApiEnum.新增失败;
                }
            }
            catch (Exception ex)
            {
                res.Message = "创建失败: " + ex.Message;
                res.Code = ApiEnum.新增失败;
            }

            return res;
        }
    }
}
